﻿#include "clientwritesession.h"
#include "utils.h"

#include <QFile>
#include <winsock.h>
namespace TFTP {


ClientWriteSession::ClientWriteSession(TransferInfo T, const QString &local, const QString &remote, TransferMode trmode)
 : TFTP::WriteSession(T)
{
	currentMode = trmode;
	currentBlock = 0;
	m_currentFile = new QFile(local);
    m_currentFile->open(QFile::WriteOnly | QFile::Append);	
	sendRequest(remote);
}


ClientWriteSession::ClientWriteSession(TransferInfo T, QIODevice *data, const QString &remote, TransferMode trmode)
 : TFTP::WriteSession(T)
{
	currentMode = trmode;
	currentBlock = 0;
	m_currentFile = data;	
	sendRequest(remote);
}


void ClientWriteSession::sendRequest(const QString &remote)
{
	QString modestring;
	switch( currentMode )
	{
		case Octet:
			modestring = "octet";
			break;
		case NetAscii:
			modestring = "netascii";
			break;
		default:
            qFatal("错误！传输操作中的模式无效！");
	}
	
    int len = 2 + remote.length() + 1 + modestring.length() + 1;

    QByteArray dgram;
    dgram.resize(len);
    wordOfArray(dgram)[0] = htons( (quint16 )RRQ );
	
//	memcpy( dgram.data()+2, remote.ascii(), remote.length() +1 );
//	memcpy( dgram.data()+2+remote.length()+1, modestring.ascii(), modestring.length() +1 );

    memcpy( dgram.data()+2, remote.data(), remote.length() +1 );
    memcpy( dgram.data()+2+remote.length()+1, modestring.data(), modestring.length() +1 );


    if( ti.sd->writeDatagram(dgram.data(), dgram.size(), ti.dAddr, ti.dPort) == -1 ){
        qWarning("发送RRQ数据包时出错 [%d]", ti.sd->error() );
    }
}

ClientWriteSession::~ClientWriteSession()
{
}

};
